<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 6/10/21
 * Time: 5:24 AM
 */

namespace app\api\controller\v1;

use app\api\model\ProductOrder;
use app\api\model\Store;
use app\api\model\StoreUser as StoreUserModel;
use app\api\model\StoreUserItem;
use app\api\model\Team as TeamModel;
use app\api\model\TeamUser as TeamUserModel;
use app\api\model\User as UserModel;
use app\api\model\UserInvitation;
use app\api\model\UserMoney as UserMoneyModel;
use app\api\service\Token as TokenService;

class AdminRank
{
    // 总量
    public function getAll()
    {
        // 总销售额
        $sale = ProductOrder::where('status','gt',1)->sum('actual_price');
        $order_count = ProductOrder::where('status','gt',1)->count();

        // 产品销量
        $whereSelf[] = ['status','gt',1];
        $volume = 0;
        $order = ProductOrder::where($whereSelf)->with('content')->select()->toArray();
        foreach ($order as $k=>$v){
            $volume += $order[$k]['content'][0]['product_number'];
        }

        // 总裂变数量
        $whereSeven = [];
        $whereSeven[] = ['type','eq',1];
        $userInvite = UserInvitation::where($whereSeven)->select()->toArray();
        $ids = array_column($userInvite,'invitee');
        $fission = 0;
        $whereNine = [];
        $whereNine[] = ['id','in',$ids];
        $whereNine[] = ['status','eq',3];
        $user = UserModel::where($whereNine)->select()->toArray();
        foreach ($user as $ka=>$va){
            $whereEight = [];
            $whereEight[] = ['user_id','eq',$user[$ka]['id']];
            $whereEight[] = ['status', 'gt', 1];
            $order = ProductOrder::where($whereEight)->find();
            if($order) {
                $fission = $fission +1;
            }
        }

        // 新客数 顾客 分享的新客数 + 扫店员二维码的新用户
        $new_user_num = 0;
        $userInviteOne = UserInvitation::where('type',2)->select()->toArray();
        $idsOne = array_column($userInviteOne,'invitee');
        $whereTen = [];
        $whereTen[] = ['id','in',$idsOne];
        $whereTen[] = ['status','eq',3];
        $whereTen[] = ['new_type','eq',1];
        $userOne = UserModel::where($whereTen)->select()->toArray();
        foreach ($userOne as $ka=>$va){
            $whereTwo = [];
            $whereTwo[] = ['user_id','eq',$userOne[$ka]['id']];
            $whereTwo[] = ['status', 'gt', 1];
            $order = ProductOrder::where($whereTwo)->find();
            if($order) {
                $new_user_num += 1;
            }
        }
        $new_user_num += $fission;

        // 总提现
        $withdrawal = UserMoneyModel::where('type',2)->sum('money');

        // 员工总销售额
        $storeUser = StoreUserModel::select()->toArray();
        $storeUserIds = array_column($storeUser,'id');
        $user_ids = array_column($storeUser,'user_id');
        $whereThree[] = ['inviter','in',$storeUserIds];
        $whereThree[] = ['type','eq',2];
        $userInvitation = UserInvitation::where($whereThree)->select()->toArray();
        $ids = array_column($userInvitation,'invitee');
        $store_user_count = ProductOrder::where('user_id','in',$ids)
            ->where('status','gt',1)
            ->sum('actual_price');
        $store_user_count_one = ProductOrder::where('user_id','in',$user_ids)
            ->where('status','gt',1)
            ->sum('actual_price');
        $store_user_count = $store_user_count + $store_user_count_one;

        // 总佣金
        $user_money_sum = UserMoneyModel::where('type',1)->sum('money');
        return [
            'sale' => $sale,
            'order_count' => $order_count,
            'new_user_count' => $new_user_num,
            'hot_pay_count' => $volume,
            'store_user_count' => $store_user_count,
            'user_money_sum' => $user_money_sum,
            'withdrawal' => $withdrawal,
            'fission_user_count' => $fission
        ];
    }

    // 店铺销售额排行
    public function getUserMoney($start_time,$end_time)
    {
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        $storeUser = StoreUserModel::where('user_id',$user['id'])->find();
        $where = [];
        if(!$start_time){
            $start_time = strtotime("-1 month");
            $end_time = time();
            $where[] = ['create_time', 'egt', $start_time];
            $where[] = ['create_time', 'elt', $end_time];
        } else {
            $where[] = ['create_time', 'egt', strtotime($start_time." 00:00:00")];
            $where[] = ['create_time', 'elt', strtotime($end_time." 23:59:59")];
        }
        $whereThree = $where;
        $whereThree[] = ['type','eq',1];
        $user_money_sum = UserMoneyModel::where($whereThree)->sum('money');
        $money = 0;
        if($user['type'] == 8) {
            $storeUserItem = StoreUserItem::where('store_user_id',$storeUser['id'])->select()->toArray();
            $storeIds = array_column($storeUserItem,'store_id');
            $store = Store::where('id','in',$storeIds)->order('id desc')->select()->toArray();
        } else {
            $store = Store::order('id desc')->select()->toArray();
        }
        $array = [];
        foreach ($store as $k=>$v){
            $storeUsers = StoreUserModel::where('store_id', $v['id'])
                ->select()->toArray();
            $ids = array_column($storeUsers,'user_id');
            $whereOne = $where;
            $whereOne[] = ['user_id','in',$ids];
            $whereOne[] = ['type','eq',1];
            $store[$k]['user_money'] = UserMoneyModel::where($whereOne)->sum('money');
            $store[$k]['user_type'] = 2;
            $money += $store[$k]['user_money'];
            array_push($array,$store[$k]);
        }
        if($user['type'] != 8) {
            array_push($array,[ 'id'=> -1, 'name'=>'顾客总佣金', 'user_money'=> ($user_money_sum-$money),'user_type' => 1]);
        }
        if(count($array) > 0) {
            $array = $this->arraySort($array,'user_money');
        }
        return $array;
    }


    /**
     * 根据门店ID查询店员信息
     */
    public function getStoreUser($store_id)
    {
        return StoreUserModel::where('store_id',$store_id)
            ->order('id desc')
            ->select()->toArray();
    }

    /**
     * 销售额明细
     *    1. 根据店员查询订单销售额信息
     */
    public function getOrderListByStoreUser($store_id,$store_user_id,$start_time,$end_time)
    {
        $where = [];
        if(!$start_time){
            $start_time = strtotime("-1 month");
            $end_time = time();
            $where[] = ['pay_time', 'egt', $start_time];
            $where[] = ['pay_time', 'elt', $end_time];
        } else {
            $where[] = ['pay_time', 'egt', strtotime($start_time." 00:00:00")];
            $where[] = ['pay_time', 'elt', strtotime($end_time." 23:59:59")];
        }
        $where[] = ['status','gt',1];
        if($store_id){
            $where[] = ['store_id','eq',$store_id];
        }
        $array = [];
        $list = ProductOrder::where($where)
            ->with('user,store')
            ->order('pay_time desc')
            ->select()->toArray();
        $storeUser = StoreUserModel::where('id',$store_user_id)->find();
        foreach ($list as $k=>$v){
            $invite = UserInvitation::where('invitee',$list[$k]['user_id'])->find();
            if($store_user_id) {
                if($invite['type'] == 2){
                    if($invite['inviter'] == $store_user_id){
                        $store_user = StoreUserModel::get($invite['inviter']);
                        $list[$k]['invite'] = UserModel::get($store_user['user_id']);
                        $list[$k]['invite']['nickname'] = $store_user['name'];
                        $list[$k]['invite']['phone'] = $store_user['phone'];
                        array_push($array, $list[$k]);
                    }
                }else{
                    if($storeUser['user_id'] == $list[$k]['user_id']) {
                        $list[$k]['invite']['nickname'] = '';
                        $list[$k]['invite']['phone'] = '';
                        array_push($array, $list[$k]);
                    }
                }
            } else {
                if($invite['type'] == 1) {
                    $list[$k]['invite'] = UserModel::get($invite['inviter']);
                }elseif($invite['type'] == 2){
                    $store_user = StoreUserModel::get($invite['inviter']);
                    $list[$k]['invite'] = UserModel::get($store_user['user_id']);
                    $list[$k]['invite']['nickname'] = $store_user['name'];
                    $list[$k]['invite']['phone'] = $store_user['phone'];
                }elseif($invite['type'] == 3){
                    $team_user = TeamUserModel::get($invite['inviter']);
                    $list[$k]['invite'] = UserModel::get($team_user['user_id']);
                    $list[$k]['invite']['nickname'] = $team_user['name'];
                    $list[$k]['invite']['phone'] = $team_user['phone'];
                }
                array_push($array,$list[$k]);
            }
        }
        return $array;
    }




    // 团员排行
    public function getTeamUserList($start_time,$end_time)
    {
        $where = [];
        if (!$start_time) {
            $start_time = strtotime("-1 month");
            $end_time = time();
            $where[] = ['pay_time', 'egt', $start_time];
            $where[] = ['pay_time', 'elt', $end_time];
        } else {
            $where[] = ['pay_time', 'egt', strtotime($start_time." 00:00:00")];
            $where[] = ['pay_time', 'elt', strtotime($end_time." 23:59:59")];
        }
        $user = UserModel::where('type', 'in', [5, 6])->select()->toArray();
        $user_ids = array_column($user, 'id');
        $teamUser = TeamUserModel::where('user_id', 'in', $user_ids)
            ->select()->toArray();
        foreach ($teamUser as $k => $v) {
            $whereTwo = [];
            $whereTwo[] = ['inviter', 'eq', $v['id']];
            $whereTwo[] = ['type', 'eq', 3];
            $userInvitation = UserInvitation::where($whereTwo)->select()->toArray();
            $ids = array_column($userInvitation, 'invitee');
            $whereThree = $where;
            $whereThree[] = ['user_id', 'in', $ids];
            $whereThree[] = ['status', 'gt', 1];
            $team_user_count = ProductOrder::where($whereThree)
                ->sum('actual_price');
            $whereFour = $where;
            $whereFour[] = ['user_id', 'eq', $v['user_id']];
            $whereFour[] = ['status', 'gt', 1];
            $team_user_count_one = ProductOrder::where($whereFour)
                ->where('status', 'gt', 1)->sum('actual_price');
            $teamUser[$k]['count'] = $team_user_count + $team_user_count_one;
        }
        if(count($teamUser) > 0) {
            $teamUser = $this->arraySort($teamUser,'count');
        }
        return $teamUser;
    }

    // 团排行
    public function getTeamList($start_time,$end_time)
    {
        $where = [];
        if (!$start_time) {
            $start_time = strtotime("-1 month");
            $end_time = time();
            $where[] = ['pay_time', 'egt', $start_time];
            $where[] = ['pay_time', 'elt', $end_time];
        } else {
            $where[] = ['pay_time', 'egt', strtotime($start_time." 00:00:00")];
            $where[] = ['pay_time', 'elt', strtotime($end_time." 23:59:59")];
        }
        $team = TeamModel::order('id desc')->select()->toArray();
        foreach ($team as $k => $v) {
            $teamUser = TeamUserModel::where('team_id', 'eq', $v['id'])
                ->select()->toArray();
            $ids = array_column($teamUser, 'id');
            $whereTwo = [];
            $whereTwo[] = ['inviter', 'in', $ids];
            $whereTwo[] = ['type', 'eq', 3];
            $userInvitation = UserInvitation::where($whereTwo)->select()->toArray();
            $user_ids = array_column($userInvitation, 'invitee');
            $whereThree = $where;
            $whereThree[] = ['user_id', 'in', $user_ids];
            $whereThree[] = ['status', 'gt', 1];
            $team_user_count = ProductOrder::where($whereThree)
                ->sum('actual_price');
            $whereFour = $where;
            $whereFour[] = ['user_id', 'in', $ids];
            $whereFour[] = ['status', 'gt', 1];
            $team_user_count_one = ProductOrder::where($whereFour)
                ->where('status', 'gt', 1)
                ->sum('actual_price');
            $team[$k]['count'] = $team_user_count + $team_user_count_one;
        }
        if(count($team) > 0) {
            $team = $this->arraySort($team,'count');
        }
        return $team;
    }



    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    public function arraySort($array, $keys, $sort = SORT_DESC) {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}